import React, {Component} from 'react';
import {connect} from 'react-redux';
import {setRoomInfoAction} from '@/store/action';
import {formatDate} from "@/common/utils";

import Avatar from "@/components/avatar";

import './index.scss';

class Chatting extends Component {
  state = {
    roomId: '',
    contacts: {},
    mine: {},
    chattingMsg: [], // 聊天数组
    draft: '', // 草稿

  }

  // 返回上一页
  goBack = () => {
    this.props.history.push('/home');
  }

  componentDidMount() {
    const {roomInfo, match} = this.props;
    // 存在房间信息
    if (typeof roomInfo[match.params.id] === 'object') {
      const {roomId, contacts, mine, chattingMsg} = roomInfo[match.params.id];
      this.setState({
        roomId, contacts, mine, chattingMsg
      }, () => {
        this.scrollBottom();
      })
    } else {
      this.goBack();
    }
  }

  // 暂存输入的内容
  bindDraft(e) {
    const val = e.target.value;
    if (val) {
      this.setState({
        draft: val
      })
    }
  }

  // 滚动到页面底部
  scrollBottom() {
    let div = document.getElementById('chattingWrap');
    window.scrollTo(0, div.scrollHeight);
  }

  // 发送消息
  sendMsg = () => {
    const {roomId, mine, draft, contacts, chattingMsg} = this.state;

    if (draft.length) {
      const {userId, username} = mine;
      chattingMsg.push({
        userId,
        username,
        time: formatDate(),
        chatContext: draft
      })
      this.setState({
        chattingMsg,
        draft: ''
      })
      this.props.setRoomInfo({
        roomId,
        contacts,
        mine,
        chattingMsg
      })
      this.scrollBottom()
      // 500ms后自动回复
      setTimeout(() => {
        this.replayMsg();
      }, 800);
    }
  }

  // 自动回复
  replayMsg() {
    const {roomId, mine, contacts, chattingMsg} = this.state;
    const {userId, username} = contacts;
    const replayMsg = ['嗯嗯', '好的啊', '你说的对', '今天天气很好'];

    chattingMsg.push({
      userId,
      username,
      time: formatDate(),
      chatContext: replayMsg[Math.floor(Math.random() * replayMsg.length)]
    })
    this.setState({
      chattingMsg: chattingMsg
    })
    this.props.setRoomInfo({
      roomId,
      contacts,
      mine,
      chattingMsg
    })
    this.scrollBottom()
  }

  render() {
    const {contacts, chattingMsg, draft} = this.state;
    const {userInfo} = this.props;

    return (
      <section className="chatting-container">
        {/*头部 对方信息*/}
        <div className="chatting-header">
          <span onClick={this.goBack}>返回</span>
          <span>{contacts.username}</span>
          <span>设置</span>
        </div>
        {/*占位div*/}
        <div className="div-seat"/>

        {/*聊天区*/}
        <div className="chatting-wrap" id="chattingWrap">
          {
            chattingMsg.map((item, index) => {
              return (
                item.userId === userInfo.userId
                  ?
                  <div className="chatting-item chat-mine" key={index}>
                    <span className="chat-txt">{item.chatContext}</span>
                    <Avatar size="small" className="mine-avatar" avatar={userInfo.avatar}/>
                  </div>
                  :
                  <div className="chatting-item" key={index}>
                    <Avatar size="small" className="contacts-avatar" avatar={contacts.avatar}/>
                    <span className="chat-txt">{item.chatContext}</span>
                  </div>
              )
            })
          }
        </div>

        {/* 发送表单 */}
        <div className="form-wrap">
          <input type="text" className="send-input" value={draft} onChange={this.bindDraft.bind(this)}/>
          <div className="send-btn" onClick={this.sendMsg}>发送</div>
        </div>
      </section>
    )
  }
}

const mapStateToProps = state => {
  return {
    userInfo: state.userInfo,
    roomInfo: state.roomInfo
  }
}
const mapDispatchToProps = dispatch => {
  return {
    setRoomInfo: (roomInfo) => dispatch(setRoomInfoAction(roomInfo))
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Chatting)
